package com.saturday.web.filter.xss;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.ValueFilter;

import java.util.List;

/**
 * @类名称 XssValueFilter.java
 * @类描述 <pre>xss-json拦截(清洗xss敏感字符)</pre>
 * </pre>
 */
public class XssValueFilter implements ValueFilter {

    /**
     * 忽略属性列表
     */
    private List<String> excludeAttr;

    public XssValueFilter(List<String> excludeAttr) {
        this.excludeAttr = excludeAttr;
    }

    @Override
    public Object process(Object o, String s, Object value) {
        if (value == null) {
            return value;
        }
        if (null != excludeAttr && excludeAttr.contains(s)) {
            return value;
        }
        if (value instanceof String) {// 字符串类型才存在 xss漏洞。
            return XssCleanUtils.xssClean((String) value);
        }
        return value;
    }

    /**
     * 是否json格式字符串
     */
    public static boolean isJson(String value) {
        try {
            JSON.parse(value);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public List<String> getExcludeAttr() {
        return excludeAttr;
    }
}
